package com.mach.platform.controller;

import com.google.common.collect.Maps;
import com.mach.platform.domain.Order;
import com.mach.platform.domain.Response;
import com.mach.platform.domain.base.Account;
import com.mach.platform.service.AccountService;
import com.mach.platform.service.ModifyOrderLogsServiceImpl;
import com.mach.platform.service.OrderFileServiceImpl;
import com.mach.platform.service.OrderServiceImpl;
import com.mach.platform.utils.security.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 *
 * 订单控制器
 */
@Slf4j
@RestController
@RequestMapping("order")
public class OrderCtrl extends BaseCtrl<Order> {

    @Autowired
    private OrderServiceImpl orderService;
    @Autowired
    private ModifyOrderLogsServiceImpl modifyOrderLogsService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private OrderFileServiceImpl orderFileService;

    /*@Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*", "*")
                    .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                    .maxAge(3600)
                    .allowCredentials(true);
        }
    }*/

    @GetMapping("/findByMain")
    public Response findByMainAndRequest(){
        Map<String, Object> result = orderService.getMain();
        return Response.ok(result);
    }

    /**
     * 查询主页面左下角订单
     * @return
     */
    @GetMapping("/getOrderByMainLeft")
    public Response getOrderByMainLeft() {
        Map<String, Object> result = orderService.getOrderByMainLeft();
        return Response.ok(result);
    }

    /**
     * 获取岗位操作布发送的订单
     * @return
     */
    @GetMapping("/getClothSending")
    public Response getClothSending(){
        Map<String, Object> result = orderService.getClothSending();
        return Response.ok(result);
    }

    /**
     * 获取岗位操作涂布段的订单
     * @return
     */
    @GetMapping("/getCoatingSection")
    public Response getCoatingSection(){
        Map<String, Object> result = orderService.getCoatingSection();
        return Response.ok(result);
    }

    /**
     * 获取岗位操作卷取段的订单
     * @return
     */
    @GetMapping("/getCoilingSection")
    public Response getCoilingSection(){
        Map<String, Object> result = orderService.getCoilingSection();
        return Response.ok(result);
    }

    /**
     * 分页查询
     * @param pageable
     * @param params
     * @return
     */
    @GetMapping("/findByPage")
    public Response findByPageAndRequest(@PageableDefault(sort = {"operation","serialNumber"}, direction = Sort.Direction.ASC) Pageable pageable, @RequestParam Map params){
        Map map = Maps.newHashMap();
        pageable.getPageNumber();
        Page<Order> result = orderService.list(pageable, params);
        int top = 0;
        int bottom = 0;

        List<Order> orders = result.getContent();
        int size = orders.size();

        if (size > 0){
            if (orders.get(0) != null && orders.get(0).getSerialNumber() != null)
            top = orders.get(0).getSerialNumber();
            if (orders.get(size - 1) != null && orders.get(size - 1).getSerialNumber() != null)
            bottom = orders.get(size - 1).getSerialNumber();
        }
        map.put("isTop", top);
        map.put("isBottom", bottom);
        map.put("data", result);
        return Response.ok(map);
    }

    /**
     * 查询一个订单
     * @param id
     * @return
     */
    @GetMapping("/getOrder")
    @Override
    public Response info(Long id) {
        Order result = orderService.info(id);
        return Response.ok(result);
    }

    /**
     * 查询岗位操作订单（待处理）
     * @param state 工作阶段
     * @return
     */
    @GetMapping("/getJob")
    public Response getJob(String state){
        Map<String, Object> result = orderService.getJob(state);
        return Response.ok(result);
    }

    /**
     * 获取未完成订单
     * @return
     */
    @GetMapping("/getAllNotFinished")
    public Response getAllNotFinished(){
        return Response.ok(orderService.getOrderNotFinish());
    }


    @Override
    public Response list(Pageable pageable, Map params) {
        return null;
    }

    /**
     * 删除多个订单
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除", notes = "接口备注：无", produces = "application/json")
    @DeleteMapping("/delete")
    public Response delete(@RequestBody Long[] ids) {
        int result = orderService.delete(ids);
        if (result > 0) {
            return Response.ok("删除成功");
        } else {
            return Response.error("删除失败");
        }
    }

    /**
     * 插入一个订单
     * @param order
     * @return
     */
    @ApiOperation(value = "保存", notes = "接口备注：无", produces = "application/json")
    @PostMapping("/addOrder")
    @Override
    public Response save(@RequestBody Order order) {
        //新插入的订单赋值最小序号
        order = orderService.getOrderSerialNumber(order);
        Order result = orderService.save(order);
        return Response.ok(result);
    }


    /**
     * 修改一个订单
     * @param record
     * @return
     */
    @ApiOperation(value = "更新", notes = "接口备注：无", produces = "application/json")
    @PostMapping("/updateOrder")
    public Response update(@RequestBody Order record){
        Order oldOrder = null;
        if (record.getId() != null) {
            oldOrder = orderService.info(record.getId());
        }
        Account account = accountService.info(SecurityUtils.getCurrentUser().getId());
        modifyOrderLogsService.save(oldOrder, record, account);
        int result = orderService.updateOrder(record);
        if (result > 0){
            return Response.ok("操作成功");
        }
        return Response.error("操作失败");
    }

    /**
     * 修改序号位置
     * @param id 订单id
     * @param direction 移动方向
     * @return
     */
    @PostMapping("/updateSerialNumber")
    public Response updateSerialNumber(Long id, String direction){
        String result = orderService.updateSerialNumber(id, direction);
        if (result.equals("操作成功")){
            return Response.ok(result);
        }
        return Response.error(result);
    }

    /**
     * 开始作业或者停止作业(完成作业)
     * @param id 订单id
     * @param workName 作业阶段()
     * @param state 状态(start  finish)
     * @return
     */
    @PostMapping("/startOrFinishWork")
    public Response startOrFinishWork(Long id, String workName, String state){
        String result = orderService.startOrFinishWork(id, workName, state);
        if (result.equals("操作成功")){
            return Response.ok(result);
        }
        return Response.error(result);
    }

    /**
     * 修改备料状态
     * @param id 订单id
     * @param state 需要修改的状态
     * @param workName 阶段名称
     * @return
     */
    @PostMapping("/updateSparePartsById")
    public Response updateSparePartsById(Long id, int state, String workName){
        String result = orderService.updateSparePartsById(id, state, workName);
        if (result.equals("操作成功")){
            return Response.ok(result);
        }
        return Response.error(result);
    }

    /**
     * 导入订单
     * @param file
     * @return
     */
    @PostMapping("/importOrder")
    public Response importOrder(@RequestParam(value="file",required = false) MultipartFile file){
        String result = null;
        try {
            result = orderService.readExcelFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result.equals("导入成功")){
            return Response.ok(result);
        }
        return Response.error(result);
    }

    /**
     * 操作条件
     * @return
     */
    @GetMapping("/operatingConditions")
    public Response operatingConditions(Long id, HttpServletResponse response){
        Order order = orderService.info(id);
        String result = orderFileService.getOrderFileFlow(order, response);
        if (result != null){
            return Response.error(result);
        }
        return null;
    }


}
